package com.leo.leetcode.s100;

/**
 *
 * @author xuexiaolei
 * @version 2017年11月20日
 */
public class T21MergeTwoSortedLists {
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode current = head;
        while (l1!=null  && l2!=null){
            if (l1.val < l2.val){
                current.next = l1;
                l1 = l1.next;
            }else {
                current.next = l2;
                l2 = l2.next;
            }
            current = current.next;
        }
        if (l1 == null) current.next = l2;
        if (l2 == null) current.next = l1;
        return head.next;
    }

    /**
     * 递归的方法写的
     * @param l1
     * @param l2
     * @return
     */
    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        if (l1 == null) // nothing left in list 1, return res list 2
        {
            return l2;
        }
        if (l2 == null) // nothing left in list 2, return rest list 1
        {
            return l1;
        }

        if (l1.val <= l2.val)
        {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        }
        else
        {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }

    public static void main(String[] args) {
        ListNode.print(mergeTwoLists(ListNode.gen(new int[]{}), ListNode.gen(new int[]{2,4,6})));
        ListNode.print(mergeTwoLists(ListNode.gen(new int[]{1,3,5}), ListNode.gen(new int[]{})));
        ListNode.print(mergeTwoLists(ListNode.gen(new int[]{1,3,5}), ListNode.gen(new int[]{2,4,6})));
        ListNode.print(mergeTwoLists(ListNode.gen(new int[]{1,3,5}), ListNode.gen(new int[]{2,4,6,7,8,9})));
    }
}
